/**
 * 索引管理器
 */
class IndexManager {
    constructor() {
        this.startIndexBtn = document.getElementById('startIndexBtn');
        this.getStatusBtn = document.getElementById('getStatusBtn');
        this.setIndexDirectoryBtn = document.getElementById('setIndexDirectoryBtn');
        this.indexStatus = document.getElementById('indexStatus');
        this.indexStatusContent = document.getElementById('indexStatusContent');
        this.pollInterval = null;
        this.init();
    }

    init() {
        if (this.startIndexBtn) {
            this.startIndexBtn.addEventListener('click', () => this.startIndexing());
        }
        
        if (this.getStatusBtn) {
            this.getStatusBtn.addEventListener('click', () => this.getIndexStatus());
        }
        
        if (this.setIndexDirectoryBtn) {
            this.setIndexDirectoryBtn.addEventListener('click', () => this.setIndexDirectories());
        }
    }

    async startIndexing() {
        const directories = this.getIndexDirectories();
        
        if (directories.length === 0) {
            this.showAlert('请至少输入一个目录路径');
            return;
        }
        
        const recursive = document.getElementById('recursiveIndex')?.checked || false;
        const force = document.getElementById('forceReindex')?.checked || false;
        
        this.setStartButtonLoading(true);
        
        try {
            const response = await window.apiClient.startIndexing(directories, recursive, force);
            
            if (response.success) {
                this.showAlert(`索引任务已启动，任务ID: ${response.data.task_id}`);
                
                // 显示索引状态区域
                this.showIndexStatus();
                
                // 开始轮询索引状态
                this.startPollingIndexStatus();
            } else {
                this.showAlert(`索引失败: ${response.message}`);
            }
        } catch (error) {
            console.error('Error starting indexing:', error);
            this.showAlert('索引失败，请检查服务器连接');
        } finally {
            this.setStartButtonLoading(false);
        }
    }

    async getIndexStatus() {
        try {
            const response = await window.apiClient.getIndexStatus();
            
            if (response.success) {
                // 显示索引状态区域
                this.showIndexStatus();
                
                // 更新状态内容
                this.updateIndexStatusContent(response.data);
            } else {
                this.showAlert(`获取状态失败: ${response.message}`);
            }
        } catch (error) {
            console.error('Error getting index status:', error);
            this.showAlert('获取状态失败，请检查服务器连接');
        }
    }

    getIndexDirectories() {
        const indexDirectoriesElement = document.getElementById('indexDirectories');
        if (!indexDirectoriesElement) return [];
        
        return indexDirectoriesElement.value
            .split('\n')
            .map(dir => dir.trim())
            .filter(dir => dir.length > 0);
    }

    setStartButtonLoading(loading) {
        if (!this.startIndexBtn) return;

        if (loading) {
            this.startIndexBtn.disabled = true;
            this.startIndexBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>索引中...';
        } else {
            this.startIndexBtn.disabled = false;
            this.startIndexBtn.innerHTML = '<i class="fas fa-play mr-2"></i>开始索引';
        }
    }

    showIndexStatus() {
        if (this.indexStatus) {
            this.indexStatus.classList.remove('hidden');
        }
    }

    updateIndexStatusContent(statusData) {
        if (!this.indexStatusContent) return;
        
        const statusHtml = `
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <p><strong>总文件数:</strong> ${statusData.total_files}</p>
                    <p><strong>已索引文件:</strong> ${statusData.indexed_files}</p>
                </div>
                <div>
                    <p><strong>总分块数:</strong> ${statusData.total_chunks}</p>
                    <p><strong>已索引分块:</strong> ${statusData.indexed_chunks}</p>
                </div>
            </div>
            <div class="mt-4">
                <p><strong>最后索引时间:</strong> ${new Date(statusData.last_indexed_time).toLocaleString()}</p>
                <p><strong>索引状态:</strong> ${statusData.is_indexing ? '进行中' : '已完成'}</p>
            </div>
        `;
        
        this.indexStatusContent.innerHTML = statusHtml;
    }

    startPollingIndexStatus() {
        // 清除之前的轮询
        this.stopPollingIndexStatus();
        
        this.pollInterval = setInterval(async () => {
            try {
                const response = await window.apiClient.getIndexStatus();
                
                if (response.success) {
                    this.updateIndexStatusContent(response.data);
                    
                    // 更新系统状态
                    this.updateSystemStatus(response.data);
                    
                    // 如果索引完成，停止轮询
                    if (!response.data.is_indexing) {
                        this.stopPollingIndexStatus();
                        this.showAlert('索引任务已完成');
                    }
                } else {
                    console.error('Failed to get index status:', response.message);
                    this.stopPollingIndexStatus();
                }
            } catch (error) {
                console.error('Error polling index status:', error);
                this.stopPollingIndexStatus();
            }
        }, 2000); // 每2秒轮询一次
    }

    stopPollingIndexStatus() {
        if (this.pollInterval) {
            clearInterval(this.pollInterval);
            this.pollInterval = null;
        }
    }

    updateSystemStatus(statusData) {
        const elements = {
            totalFiles: document.getElementById('totalFiles'),
            indexedFiles: document.getElementById('indexedFiles'),
            totalChunks: document.getElementById('totalChunks'),
            indexedChunks: document.getElementById('indexedChunks')
        };

        if (elements.totalFiles) elements.totalFiles.textContent = statusData.total_files || 0;
        if (elements.indexedFiles) elements.indexedFiles.textContent = statusData.indexed_files || 0;
        if (elements.totalChunks) elements.totalChunks.textContent = statusData.total_chunks || 0;
        if (elements.indexedChunks) elements.indexedChunks.textContent = statusData.indexed_chunks || 0;
    }

    async loadSystemStatus() {
        try {
            const response = await window.apiClient.getIndexStatus();
            
            if (response.success) {
                this.updateSystemStatus(response.data);
            } else {
                console.error('Failed to load system status:', response.message);
            }
        } catch (error) {
            console.error('Error loading system status:', error);
        }
    }

    showAlert(message) {
        alert(message);
    }
    
    async setIndexDirectories() {
        const directories = this.getIndexDirectories();
        
        if (directories.length === 0) {
            this.showAlert('请至少输入一个目录路径');
            return;
        }
        
        try {
            const response = await window.apiClient.setIndexDirectories(directories);
            
            if (response.success) {
                this.showAlert('索引目录设置成功');
            } else {
                this.showAlert(`设置失败: ${response.message}`);
            }
        } catch (error) {
            console.error('Error setting index directories:', error);
            this.showAlert('设置失败，请检查服务器连接');
        }
    }
}

// 创建全局索引管理器实例
window.indexManager = new IndexManager();